package com.xbongbong.saas.model.impl;

import com.alibaba.fastjson.JSONObject;
import com.xbongbong.paas.constant.PaasConstant;
import com.xbongbong.paas.domain.entity.PaasFormDataEntity;
import com.xbongbong.paas.elasticsearch.model.PaasEsModel;
import com.xbongbong.paas.elasticsearch.pojo.dto.InsertDTO;
import com.xbongbong.paas.enums.DelEnum;
import com.xbongbong.paas.enums.FieldTypeEnum;
import com.xbongbong.paas.enums.IndexTypeEnum;
import com.xbongbong.paas.help.subform.TransferSubFormHelper;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.DateTimeUtil;
import com.xbongbong.paas.toolbox.util.DateUtil;
import com.xbongbong.saas.constant.BasicConstant;
import com.xbongbong.saas.constant.ParameterConstant;
import com.xbongbong.saas.constant.StringConstant;
import com.xbongbong.saas.domain.dao.PayPlanUserDao;
import com.xbongbong.saas.domain.entity.PayPlanUserEntity;
import com.xbongbong.saas.domain.entity.UserTeamEntity;
import com.xbongbong.saas.enums.subform.ContactTeamEnum;
import com.xbongbong.saas.enums.subform.PaymentSheetTeamEnum;
import com.xbongbong.saas.model.PayPlanUserModel;
import org.elasticsearch.action.support.WriteRequest;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * @author haibin.zhang
 * @version v1.0
 * @date 2019/4/11 15:13
 * @since v1.0
 */
@Component
@Service("payPlanUserModel")
public class PayPlanUserModelImpl implements PayPlanUserModel {
    @Resource
    private PayPlanUserDao payPlanUserDao;
    @Resource
    private PaasEsModel paasEsModel;
    @Resource
    private TransferSubFormHelper transferSubFormHelper;


    @Override
    public List<PayPlanUserEntity> findEntitys(Map<String, Object> param) {
        return payPlanUserDao.findEntitys(param);
    }

    @Override
    public Integer save(PayPlanUserEntity PayPlanUserEntity) throws XbbException {
        if (PayPlanUserEntity.getId() == null || PayPlanUserEntity.getId().equals(0L)) {
            return insert(PayPlanUserEntity);
        }
        return update(PayPlanUserEntity);
    }

    @Override
    public PayPlanUserEntity getByKey(Long key, String corpid) {
        return payPlanUserDao.getByKey(key,corpid);
    }

    @Override
    public List<PayPlanUserEntity> findAllEntitys(Map<String, Object> param) {
        return null;
    }

    @Override
    public void disbandedTeamByCustomerId(String corpid, List<Long> customerIdList) throws XbbException {

    }

    @Override
    public void delete(PayPlanUserEntity payPlanUserEntity) throws XbbException {
        payPlanUserEntity.setDel(1);
        payPlanUserEntity.setUpdateTime((long) DateUtil.getInt());
        payPlanUserDao.update(payPlanUserEntity);
        paasEsModel.delete(payPlanUserEntity.getId(), payPlanUserEntity.getCorpid(), IndexTypeEnum.IDX_SAAS_PAY_PLAN_TEAM, payPlanUserEntity.getDataId());
//        paasEsModel.update(payPlanUserEntity,IndexTypeEnum.IDX_SAAS_PAY_PLAN_TEAM,payPlanUserEntity.getCorpid(),payPlanUserEntity.getId(),payPlanUserEntity.getDataId());
    }

    @Override
    public List<UserTeamEntity> findBaseEntitys(Map<String, Object> map) {
        return payPlanUserDao.findBaseEntitys(map);
    }

    @Override
    public Integer deleteByContractIdIn(List<Long> contractIdIn, String corpid) throws XbbException {
        return null;
    }

    @Override
    public List<Long> getDataIdList(String corpid, Integer isMain, List<String> userId) {
        return null;
    }

    @Override
    public void insertBatch(List<PayPlanUserEntity> PayPlanUserEntityList) throws XbbException {
        insertBatch(PayPlanUserEntityList, WriteRequest.RefreshPolicy.NONE);
    }

    @Override
    public void insertBatch(List<PayPlanUserEntity> PayPlanUserEntityList, WriteRequest.RefreshPolicy refreshPolicy) throws XbbException {
        payPlanUserDao.insertBatch(PayPlanUserEntityList);
        List<PaasFormDataEntity> paasFormDataEntities = transferSubFormHelper.transferUserTeamToFormDataList(IndexTypeEnum.IDX_SAAS_PAY_PLAN_TEAM, PayPlanUserEntityList);

        List<InsertDTO> insertDTOList = new ArrayList<>();
        for (PaasFormDataEntity paasFormDataEntity : paasFormDataEntities) {
            insertDTOList.add(paasEsModel.getSaveDTO(paasFormDataEntity, IndexTypeEnum.IDX_SAAS_PAY_PLAN_TEAM));
        }

        paasEsModel.insertBatch(insertDTOList, refreshPolicy);
    }

    @Override
    public void batchDelete(String corpid, List<PayPlanUserEntity> removeList) throws XbbException {
        List<Long> removeIdList = new ArrayList<>();
        removeList.forEach(entity -> removeIdList.add(entity.getId()));
        payPlanUserDao.batchDeleteById(corpid, removeIdList);
        List<InsertDTO> insertDTOList = new ArrayList<>();
        for (PayPlanUserEntity entity : removeList){
            InsertDTO insertDTO = new InsertDTO();
            insertDTO.setEsId(IndexTypeEnum.IDX_SAAS_PAY_PLAN_TEAM.getType() + "_" + corpid + "_" + entity.getId());
            insertDTO.setParent(corpid + "_" + entity.getDataId());
            insertDTO.setIndexTypeEnum(IndexTypeEnum.IDX_SAAS_PAY_PLAN_TEAM);
            insertDTO.setIndex(IndexTypeEnum.IDX_SAAS_PAY_PLAN_TEAM.getIndex());
            insertDTO.setType(IndexTypeEnum.IDX_SAAS_PAY_PLAN_TEAM.getType());
            Map<String,Object> sourceMap = new HashMap<>();
            sourceMap.put(StringConstant.UPDATE_TIME, DateTimeUtil.getInt());
            sourceMap.put(StringConstant.DEL,DelEnum.DELETE.getDel());
            insertDTO.setSource(sourceMap);
            insertDTOList.add(insertDTO);
        }
        paasEsModel.updateBatch(insertDTOList);
    }

    @Override
    public void batchUpdateByUserIdIn(String corpid, List<Long> dataIdIn, List<UserTeamEntity> teamEntityList, Integer isMain, Integer del) throws XbbException {
        batchUpdateByUserIdIn(corpid, dataIdIn, teamEntityList, isMain, del, WriteRequest.RefreshPolicy.WAIT_UNTIL);
    }

    @Override
    public void batchUpdateByUserIdIn(String corpid, List<Long> dataIdIn, List<UserTeamEntity> teamEntityList, Integer isMain, Integer del, WriteRequest.RefreshPolicy refreshPolicy) throws XbbException {
        payPlanUserDao.batchUpdateByIdIn(corpid, dataIdIn, isMain, del);

        List<InsertDTO> insertList = new ArrayList<>();

        for (UserTeamEntity userTeamEntity : teamEntityList) {
            InsertDTO insertDTO = new InsertDTO();
            insertDTO.setEsId(IndexTypeEnum.IDX_SAAS_PAY_PLAN_TEAM.getType() + "_" + corpid + "_" + userTeamEntity.getId());
            insertDTO.setParent(corpid + "_" + userTeamEntity.getDataId());
            Map<String, Object> map = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            if (Objects.nonNull(isMain)) {
                JSONObject object = new JSONObject();
                object.put(ContactTeamEnum.IS_MAIN.getDataAttr(), isMain);
                map.put(StringConstant.JSON_DATA, object);
            }
            if (Objects.nonNull(del)) {
                map.put(ParameterConstant.DEL, del);
            }
            map.put(FieldTypeEnum.UPDATETIME.getAlias(), DateTimeUtil.getInt());
            insertDTO.setSource(map);
            insertDTO.setIndexTypeEnum(IndexTypeEnum.IDX_SAAS_PAY_PLAN_TEAM);
            insertList.add(insertDTO);
        }
        paasEsModel.updateBatch(insertList, refreshPolicy);
    }

    /**
     * 编辑协同人权限
     *
     * @param shouldUpdateEntity
     */
    @Override
    public void updateEditFormPer(PayPlanUserEntity shouldUpdateEntity) throws XbbException{
        updateFormTeam(shouldUpdateEntity);
    }

    /**
     * 编辑标签
     *
     * @param payPlanUserEntity
     * @throws XbbException
     */
    @Override
    public void editLabel(PayPlanUserEntity payPlanUserEntity) throws XbbException {
        updateFormTeam(payPlanUserEntity);
    }

    @Override
    public Integer insert(PayPlanUserEntity entity) throws XbbException {
        long now = DateTimeUtil.getInt();
        entity.setAddTime(now);
        entity.setUpdateTime(now);
        Integer result = payPlanUserDao.insert(entity);
        PaasFormDataEntity paasFormDataEntity = transferSubFormHelper.transferUserTeamToFormData(IndexTypeEnum.IDX_SAAS_PAY_PLAN_TEAM, entity);
        InsertDTO saveDTO = paasEsModel.getSaveDTO(paasFormDataEntity, IndexTypeEnum.IDX_SAAS_PAY_PLAN_TEAM);
        paasEsModel.insert(saveDTO);
        return result;
    }

    @Override
    public Integer update(PayPlanUserEntity entity) throws XbbException {
        long now = DateTimeUtil.getInt();
        entity.setUpdateTime(now);
        Integer result =  payPlanUserDao.update(entity);
        PaasFormDataEntity paasFormDataEntity = transferSubFormHelper.transferUserTeamToFormData(IndexTypeEnum.IDX_SAAS_PAY_PLAN_TEAM, entity);
        InsertDTO saveDTO = paasEsModel.getSaveDTO(paasFormDataEntity, IndexTypeEnum.IDX_SAAS_PAY_PLAN_TEAM);
        paasEsModel.update(saveDTO);

        return result;
    }

    @Override
    public Integer getEntitysCount(Map<String, Object> param) {
        return payPlanUserDao.getEntitysCount(param);
    }

    @Override
    public List findEntitysWithoutSub(Map<String, Object> param) {
        return null;
    }

    private void updateFormTeam(PayPlanUserEntity payPlanUserEntity) throws XbbException {
        Long updateTime = DateTimeUtil.getInt();
        payPlanUserEntity.setUpdateTime(updateTime);
        payPlanUserDao.update(payPlanUserEntity);
        InsertDTO insertDTO = new InsertDTO();
        String corpid = payPlanUserEntity.getCorpid();
        insertDTO.setEsId(IndexTypeEnum.IDX_SAAS_PAY_PLAN_TEAM.getType() + "_" + corpid + "_" + payPlanUserEntity.getId());
        insertDTO.setParent(corpid + "_" + payPlanUserEntity.getDataId());
        Map<String, Object> map = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        map.put("updateTime", updateTime);
        insertDTO.setSource(map);
        insertDTO.setIndexTypeEnum(IndexTypeEnum.IDX_SAAS_PAY_PLAN_TEAM);
        paasEsModel.update(insertDTO);
    }

    /**
     * 批量更新团队的人员为协同人身份以及协同人的可编辑权限
     *
     * @param corpid
     * @param idIn
     * @param teamEntityList
     * @param isMain
     * @param needThrow
     * @throws XbbException
     */
    @Override
    public void batchUpdateCoAndPerByUserIdIn(String corpid, List<Long> idIn, List<UserTeamEntity> teamEntityList, Integer isMain, boolean needThrow) throws XbbException {
        batchUpdateCoAndPerByUserIdIn(corpid, idIn, teamEntityList, isMain, needThrow, WriteRequest.RefreshPolicy.WAIT_UNTIL);
    }

    @Override
    public void batchUpdateCoAndPerByUserIdIn(String corpid, List<Long> idIn, List<UserTeamEntity> teamEntityList, Integer isMain, boolean needThrow, WriteRequest.RefreshPolicy refreshPolicy) throws XbbException {
        Integer formPermission = teamEntityList.get(BasicConstant.ZERO).getFormPermission();
        payPlanUserDao.batchUpdateCoAndPerByUserIdIn(corpid, idIn, isMain, formPermission);
        List<InsertDTO> insertList = new ArrayList<>();
        for (UserTeamEntity userTeamEntity : teamEntityList) {
            InsertDTO insertDTO = new InsertDTO();
            insertDTO.setEsId(IndexTypeEnum.IDX_SAAS_PAY_PLAN_TEAM.getType() + "_" + corpid + "_" + userTeamEntity.getId());
            insertDTO.setParent(corpid + "_" + userTeamEntity.getDataId());
            Map<String, Object> map = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            if (Objects.nonNull(isMain)) {
                JSONObject object = new JSONObject();
                object.put(PaymentSheetTeamEnum.IS_MAIN.getDataAttr(), isMain);
                map.put(StringConstant.JSON_DATA, object);
            }
            map.put(FieldTypeEnum.UPDATETIME.getAlias(), DateTimeUtil.getInt());
            insertDTO.setSource(map);
            insertDTO.setIndexTypeEnum(IndexTypeEnum.IDX_SAAS_PAY_PLAN_TEAM);
            insertList.add(insertDTO);
        }
        paasEsModel.updateBatch(insertList, refreshPolicy, needThrow);
    }
}
